#!/usr/bin/python
# -*- coding: utf-8 -*-

#import numpy as np
#import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import argparse
import sys
from datetime import datetime
from matplotlib.dates import date2num


import photodb

def hist(data, title=None, xlabel=None, ylabel=None, minval=None, maxval=None):
    #n, bins, patches = plt.hist(data, 50, normed=1, facecolor='green', alpha=0.75)
    rangelimits = (minval, maxval)
    if (minval == None):
        minval = min(data)
    else:
        minval = float(minval)
    if (maxval == None):
        maxval = max(data)
    else:
        maxval = float(maxval)

    bins = 20
    #maxval = 10
    #bins = [0, 0.001, 0.01, 0.1, 1, 5, 10]
    n, bins, patches = plt.hist(data, bins, range=(minval, maxval), normed=0, facecolor='green', alpha=0.75, rwidth= 1)
    #plt.bar(range(len(n)), n)
    print n
    print bins
    if title:
        plt.title(title)
    if (xlabel):
        plt.xlabel(xlabel)
    if (ylabel):
        plt.ylabel(ylabel)
    plt.show()
    
def main():

    parser = argparse.ArgumentParser(description='exifplot', epilog="Author: Juuso Räsänen")
    parser.add_argument('file', nargs='*', help="Image file name")
    parser.add_argument('-debug', '-d', action='store_true', help='Print some additional debug info')

    #parser.add_argument('-hist', help='Plot a histogram of values with this KEY')
    parser.add_argument('-field', default='ot', help='The metadata field to plot')
    parser.add_argument('-minval', default=None, help='Minimum value for x')
    parser.add_argument('-maxval', default=None, help='Maximum value for x')

    args = parser.parse_args()

    files = args.file

    if (not files):
        files = []
        # Read file from stdin (one per line, up-to first tab char)
        for line in sys.stdin.readlines():
            n = line.find('\t')
            if (n > 0):
                line = line[0:n]
            else:
                line = line.rstrip()
            files.append(line)
        
    vals = []
    db = photodb.PhotoDB(mode='normal')
    ignored = 0
#    keys = args.field
    key = args.field
    for fname in files:
        #entry = photodb.PhotoDBEntry(fname)
        entry = db.getEntry(fname)

        try:
            if (key=='ot'):
                vals.append(date2num(datetime.strptime(str(entry[key]),'%Y-%m-%d %H:%M:%S')))
            else:
                vals.append(float(entry[key]))
        except:
            ignored += 1
            pass
    #print vals
    sys.stderr.write('Warning: Ignored %d files.\n' % ignored)
    hist(vals, args.field, 'Value', 'Count', minval=args.minval, maxval=args.maxval)


if __name__ == "__main__":
    main()

